package com.example.demo.mapper;


import com.example.demo.entity.Image;
import com.example.demo.entity.Type;
import com.example.demo.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class TypeMapper {

//    类型全部查找
    public List<Type> TypeSelect() throws Exception{
        List<Type> typelist=new ArrayList<Type>();
        Type newtype=null;
        Connection con = DBUtil.getConnection();
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("select * from Type ");

        while (rs.next()){
            newtype=new Type();
            newtype.setType_id(rs.getInt("type_id"));
            newtype.setType_name(rs.getString("type_name"));
            typelist.add(newtype);
        }
        return typelist;
    }


//    根据类型找图片
    public List<Image> TypeImageSelect(int type_id) throws Exception{
        List<Image> imagelist=new ArrayList<Image>();
        Image newimage=null;
        Connection con = DBUtil.getConnection();
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("select * from Image left join Type on Image.type_id = Type.type_id where Type.type_id="+type_id);

        while (rs.next()){
            newimage=new Image();
            newimage.setTitle(rs.getString("title"));
            newimage.setImagehttps(rs.getString("Imagehttps"));
            newimage.setFormerImagehttp(rs.getString("FormerImagehttp"));
            newimage.setType(rs.getInt("type_id"));
            imagelist.add(newimage);
        }
        return imagelist;
    }

//    修改类型名称
    public void Typeupdate (int type_id,String newType_name) throws Exception{
        Connection con=DBUtil.getConnection();
        String sql="update Type" +
                "set type_name = ?" +
                "where type_id = ? ";
        PreparedStatement psmt=con.prepareStatement(sql);
        psmt.setString(1,newType_name);
        psmt.setInt(2,type_id);
        psmt.execute();
    }

//    增加类型
    public void TypeAdd(String Type_name)throws Exception{
        Connection con = DBUtil.getConnection();
        String sql="insert into Type "
                + "(type_name) "
                + "values( "
                + "?)";
        PreparedStatement psmt = con.prepareStatement(sql);
        psmt.setString(1, Type_name);
        psmt.execute();
    }

//    删除类型
    public void TypeDelete(int Type_id)throws Exception{
        Connection con=DBUtil.getConnection();
        String sql="" +
                "DELETE FROM Type "+
                "WHERE Type_id = ? ";
        PreparedStatement psmt=con.prepareStatement(sql);
        psmt.setInt(1,Type_id);

        psmt.execute();
   }
}
